package com.outsider.music.service;

import java.io.File;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.core.JFinalFilter;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Log;
import com.outsider.music.dao.Music;
import com.outsider.music.dao.Playlist;
import com.outsider.util.OkHttp3;
import com.outsider.util.music.BaiduMusic;
import com.outsider.util.music.Netease;
import com.outsider.util.music.XiamiMusic;

public class MusicService {
	public String getUrl(Music music) {
		final String path = PathKit.getWebRootPath() + File.separator + "music" + File.separator + music.getSource()
				+ File.separator + music.getSinger().trim() + File.separator + music.getAlbum().trim();
		final String name = music.getName() + ".mp3";
		File file=new File(path+File.separator+name);
		boolean dataBaseExist=Music.dao.isExist(music.getSource(), music.getSourceID());
		boolean fileExist=file.exists();
		String url = null;
		if ((dataBaseExist == false) || (fileExist==false)) {
			if (music.getSource().equals(com.outsider.util.music.Music.SOURCE_BAIDU))
				url = BaiduMusic.getURL(music.getSourceID());
			if (music.getSource().equals(com.outsider.util.music.Music.SOURCE_XIAMI))
				url = XiamiMusic.getURL(music.getSourceID());
			if (music.getSource().equals(com.outsider.util.music.Music.SOURCE_NETEASE))
				url = Netease.getURL(music.getSourceID());
			final String urlF = url;
			Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					OkHttp3 okHttp3 = OkHttp3.getInstance();
					boolean bo=okHttp3.download(urlF, path, name);
					if (bo) {
						if (dataBaseExist==false) music.save();
						Logger.getLogger("").info(name+" download Success");
					}
					else
						Logger.getLogger("").info(urlF+" download Fail");
				}
			});
			thread.start();
			return url;
		}

		
		return path+File.separator+name;
	}
    public void createPlaylist(Playlist playlist,com.outsider.util.music.Music music){
    	JSONArray json=new JSONArray();
    	json.add(music);
    	playlist.setJson(json.toString().getBytes());
    	playlist.save();
    }
	public void addPlaylist(Playlist playlist, com.outsider.util.music.Music music) {
		JSONArray json=JSONArray.parseArray(new String(playlist.getJson()));
		json.add(music);
    	playlist.setJson(json.toString().getBytes());
    	playlist.update();
		
		
	}
	public void removePlaylist(Playlist playlist, String songID) {
		JSONArray json=JSONArray.parseArray(new String(playlist.getJson()));
		for (int i=0;i<json.size();i++){
			if (json.getJSONObject(i).getString("iD").equals(songID)){
				json.remove(i);
				break;
			}
				
		}
    	playlist.setJson(json.toString().getBytes());
    	playlist.update();
	}
}
